/**
 * 
 */
package com.roc.web.action;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.pojo.Operators;
import com.roc.bean.JsonBean;
import com.roc.page.BaseAction;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.util.MD5Utils;
import com.roc.util.constant.Constant;

import net.sf.json.JSONObject;

/**
 * 忘记密码
 * 
 * @author Administrator
 *
 */
@Component
@Namespace("/forget")
@Scope("prototype")
public class ForgetPwdAction extends BaseAction {
    static Logger logger = LogManager.getLogger(ForgetPwdAction.class);

    private String accountNo;

    private String json;

    private String mobile;

    private String verifyCode;

    private String newPassWord;

    private String rePassWord;


    @Autowired
    private IMerchantServices merchantServices;

    /**
     * 忘记密码页面
     * 
     * @return
     */
    @Action(value = "forgetPwdPage", results = {
            @Result(name = SUCCESS, location = "/pages/operator/forgetPwd.jsp") }, interceptorRefs = @InterceptorRef("defaultStack"))
    public String forgetPwdPage() {
        getRequest().setAttribute("flag", 1);//
        return SUCCESS;
    }

    /**
     * 查询登录名是否存在 ******返回json 类型报错，所以返回流
     */
    @Action(value = "getForgetPwdAccount", interceptorRefs = @InterceptorRef("defaultStack"))
    public void getAccoutNo() {
        PrintWriter pw = null;
        try {
            getResponse().setCharacterEncoding("utf-8");
            pw = getResponse().getWriter();
            JsonBean jsonBean = merchantServices.queryOperatorByAccountNo(accountNo.trim());
            json = JSONObject.fromObject(jsonBean).toString();
            logger.info("=====查询登录名json-->[" + json + "]====");
            pw.write(json);
        } catch (Exception e) {
            JsonBean js = new JsonBean();
            js.setCode("0000");
            js.setCodeDesc("");
            json = JSONObject.fromObject(js).toString();
            pw.write(json.toString());
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    /**
     * 跳转到发短信页面
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "sentMsgPage", results = {
            @Result(name = "success", location = "/pages/operator/forgetPwd.jsp") }, interceptorRefs = @InterceptorRef("defaultStack"))
    public String sentMsgPage() throws Exception {
        
        mobile = merchantServices.queryPhoneByAccountNo(accountNo.trim());
        
        if(null != mobile && mobile.length() == 11){
            getRequest().setAttribute("mobileDesc", mobile.substring(0, 3) + "****" + mobile.substring(7));//
        }else{
            getRequest().setAttribute("mobileDesc", mobile);//
            getRequest().setAttribute("msg", "该手机号不正确"+mobile);//
            getRequest().setAttribute("flag", 1);//
            return SUCCESS;
        }
        
        logger.info("登录名"+accountNo+"手机号为"+mobile);
        getRequest().getSession().setAttribute("accountNo", accountNo.trim());//
        logger.info("将登录名"+accountNo+"放入session中");
        getRequest().setAttribute("flag", 2);//
        return SUCCESS;
    }

    /**
     * 发送短信验证码
     */
    @Action(value = "sendMsg", interceptorRefs = @InterceptorRef("defaultStack"))
    public void sendMsg() {
        PrintWriter pw = null;
        try {
            getResponse().setCharacterEncoding("utf-8");
            pw = getResponse().getWriter();
            String accountNo = (String) getRequest().getSession().getAttribute("accountNo");
            
            String verifyCode = String.valueOf((int)((Math.random()*9+1)*100000));
            getRequest().getSession().setAttribute("verifyCode",verifyCode);//
            logger.info("=====将验证码保存到session中-->[" + verifyCode + "]====");
            JsonBean jsonBean = merchantServices.sendMsg( accountNo.trim(),verifyCode);
            String  msg = JSONObject.fromObject(jsonBean).toString();
            json = jsonBean.getCode();
            if(jsonBean.getCode().equals("1")){
                logger.info("=====发送验证码成功json-->[" + msg  + "]====");
            }else if(jsonBean.getCode().equals("0")){
                logger.info("=====发送验证码失败json-->[" + json + "]====");
            }
            pw.write(json);
        } catch (Exception e) {
            JsonBean js = new JsonBean();
            js.setCode("0000");
            js.setCodeDesc("");
            json = JSONObject.fromObject(js).toString();
            pw.write(json.toString());
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    /**
     * 校验用户输入的验证码是否正确
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "validateCode", interceptorRefs = @InterceptorRef("defaultStack"))
    public void validateCode() {
        PrintWriter pw = null;
        try {
            JsonBean jsonBean = new JsonBean();
            getResponse().setCharacterEncoding("utf-8");
            String validateCode = (String) getRequest().getSession().getAttribute("verifyCode");
            if (!verifyCode.equals(validateCode)) {
                jsonBean.setCode("0");
                jsonBean.setCodeDesc("验证码错误");
            } else {
                jsonBean.setCode("1");
                jsonBean.setCodeDesc("验证码正确");
             
                //验证成功将code码保存到session中
                getRequest().getSession().setAttribute("code",jsonBean.getCode());//
                logger.info("=====将code码保存到session中-->[" + jsonBean.getCode() + "]====");
            }
            pw = getResponse().getWriter();
            json = JSONObject.fromObject(jsonBean).toString();
            logger.info("=====校验验证码json-->[" + json + "]====");
            pw.write(json);
        } catch (Exception e) {
            JsonBean js = new JsonBean();
            js.setCode("0000");
            js.setCodeDesc("");
            json = JSONObject.fromObject(js).toString();
            pw.write(json.toString());
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }

    /**
     * 设置密码页面
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "setPwdPage", results = {
            @Result(name = "success", location = "/pages/operator/forgetPwd.jsp") }, interceptorRefs = @InterceptorRef("defaultStack"))
    public String setPwdPage() throws Exception {
        String validateCode = (String) getRequest().getSession().getAttribute("verifyCode");
        if (!verifyCode.equals(validateCode)) {
            getRequest().setAttribute("msg", "验证码错误");//
            getRequest().setAttribute("flag", 2);//
            return SUCCESS;
        }
        getRequest().setAttribute("flag", 3);//
        return SUCCESS;
    }

    /**
     * 设置密码
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "setPwdSubmit", results = {
            @Result(name = "success", location = "/pages/operator/forgetPwd.jsp"),
            @Result(name = "input", location = "/pages/redirect.jsp") }, interceptorRefs = @InterceptorRef("defaultStack"))
    public String modifySubmit() throws Exception {
        Operators merchant;
        String msg;
        String accountNo = (String) getRequest().getSession().getAttribute("accountNo");
        String code = (String) getRequest().getSession().getAttribute("code");
        logger.info("accountno-->"+accountNo+"-----code->"+code);
        if (accountNo != null && code.equals("1")   ) {
        	logger.info(" --开始判断--");
            merchant = merchantServices.findMerchantByNo(accountNo);
            if (!newPassWord.equals(rePassWord)) {
                msg = "新密码与确认密码不一致，请重新输入！！！";
                getRequest().setAttribute("flag", 3);//
                getRequest().setAttribute("msg", msg);
                return SUCCESS;
            }
           int j = 0;
            if (newPassWord != null && Pattern.compile("(?i)[a-z]").matcher(newPassWord).find()) {
                // 有字母
                j++;
            }

            if (newPassWord != null && Pattern.compile("(?i)[0-9]").matcher(newPassWord).find()) {
                // 有 数字
                j++;
            }
            if (j < 2) {
                msg = "新密码必须包含字符和数字！请重新输入";
                getRequest().setAttribute("flag", 3);//
                getRequest().setAttribute("msg", msg);
                return SUCCESS;
            }
            if (newPassWord.length() < 7 && newPassWord.length() > 12) {
                msg = "密码不能少于6位，不能大于12位！请重新输入";
                getRequest().setAttribute("flag", 3);//
                getRequest().setAttribute("msg", msg);
                return SUCCESS;
            }

            merchant.setPwd(MD5Utils.MD5Encode(newPassWord));
            String time = "";
            Date dt = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            time = sdf.format(dt);
            merchant.setUpdatePWD(time);
            try {
                merchant = merchantServices.modifyPwd(merchant);
                ServletActionContext.getRequest().getSession().setAttribute(Constant.SESSION_LOGIN_MERCHANT,
                        merchant);
                getRequest().setAttribute("flag", 4);//
                logger.info("------------用户【" + merchant.getAccountNo() + "】修改密码成功！---------------");
                getRequest().getSession().removeAttribute("code"); //清除
                getRequest().getSession().removeAttribute("accountNo"); //清除
                getRequest().getSession().removeAttribute("verifyCode");//清除
                return SUCCESS;
            } catch (ServiceException e) {
                msg = e.getMessage();
                logger.info("------------用户【" + merchant.getAccountNo() + "】修改密码失败！---------------");
                logger.error(e.getMessage(), e);
                return SUCCESS;
            }
        }else{
	        msg = "验证未通过";
	        getRequest().setAttribute("msg", msg);
	        getRequest().setAttribute("flag", 1);//
        }
        return SUCCESS;
    }

    /**
     * 跳转到登录页面
     * 
     * @return
     * @throws Exception
     */
    @Action(value = "returnLoginPage", results = {
            @Result(name = "success", location = "/pages/redirect.jsp") })
    public String returnLoginPage() throws Exception {
        return SUCCESS;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getVerifyCode() {
        return verifyCode;
    }

    public void setVerifyCode(String verifyCode) {
        this.verifyCode = verifyCode;
    }


    public String getNewPassWord() {
        return newPassWord;
    }

    public void setNewPassWord(String newPassWord) {
        this.newPassWord = newPassWord;
    }

    public String getRePassWord() {
        return rePassWord;
    }

    public void setRePassWord(String rePassWord) {
        this.rePassWord = rePassWord;
    }

}
